package buaa.qel.rpc.client.loadbalance.impl;

import buaa.qel.rpc.client.handler.RpcClientHandler;
import buaa.qel.rpc.client.loadbalance.RpcLoadBalance;
import buaa.qel.rpc.common.info.RegistryNodeInfo;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
public class RpcLoadBalanceRoundRobin extends RpcLoadBalance {
    private AtomicInteger roundRobin = new AtomicInteger(0);

    public RegistryNodeInfo doRoute(List<RegistryNodeInfo> addressList) {
        int size = addressList.size();
        int index = roundRobin.getAndAdd(1) % size;
        return addressList.get(index);
    }

    @Override
    public RegistryNodeInfo route(String serviceKey, Map<RegistryNodeInfo, RpcClientHandler> connectedServerNodes) throws Exception {
        Map<String, List<RegistryNodeInfo>> serviceMap = getServiceMap(connectedServerNodes);
        List<RegistryNodeInfo> addressList = serviceMap.get(serviceKey);
        log.info("{}",addressList.size());
        if (addressList != null && addressList.size() > 0) {
            return doRoute(addressList);
        } else {
            throw new Exception("Can not find connection for service: " + serviceKey);
        }
    }
}
